/**
 * @作者 伟子涵
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2023/12/20  17:36
 */
package com.itzhouwei.minis.beans.factory.xml;

import com.itzhouwei.minis.beans.BeanDefinition;
import com.itzhouwei.minis.beans.factory.BeanFactory;
import com.itzhouwei.minis.beans.factory.SimpleBeanFactory;
import com.itzhouwei.minis.beans.factory.config.ArgumentValue;
import com.itzhouwei.minis.beans.factory.config.ArgumentValues;
import com.itzhouwei.minis.beans.factory.config.PropertyValue;
import com.itzhouwei.minis.beans.factory.config.PropertyValues;
import com.itzhouwei.minis.core.Resource;
import org.dom4j.Element;

import java.util.List;

/**
 * @description:
 * @author：zw，微信：yingshengzw
 * @date: 2023/12/20  17:36
 * @Copyright： 公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、分享、成长，让自己和他人都能有所收获！
 */
public class XmlBeanDefinitionReader {



    SimpleBeanFactory simpleBeanFactory;

    public XmlBeanDefinitionReader(SimpleBeanFactory simpleBeanFactory) {
        this.simpleBeanFactory = simpleBeanFactory;
    }

    public void loadBeanDefinitions(Resource resource) {
        // 1. 读取配置文件，获取到配置文件的字节流
        // 2. 将字节流转换成输入流
        // 3. 解析配置文件，获取到BeanDefinition对象
        // 4. 将BeanDefinition对象注册到容器中

        while (resource.hasNext()) {
            Element element = (Element)resource.next();
            String beanID = element.attributeValue("id");
            String beanClassName = element.attributeValue("class");

            BeanDefinition beanDefinition = new BeanDefinition(beanID, beanClassName);

            // handle properties
            List<Element> propertyElements = element.elements("property");
            PropertyValues PVS = new PropertyValues();
            for (Element e : propertyElements) {
                String pType = e.attributeValue("type");
                String pName = e.attributeValue("name");
                String pValue = e.attributeValue("value");
                PVS.addPropertyValue(new PropertyValue(pType, pName, pValue));
            }
            beanDefinition.setPropertyValues(PVS);
            //end of handle properties

            //get constructor
            List<Element> constructorElements = element.elements("constructor-arg");
            ArgumentValues AVS = new ArgumentValues();
            for (Element e : constructorElements) {
                String pType = e.attributeValue("type");
                String pName = e.attributeValue("name");
                String pValue = e.attributeValue("value");

                AVS.addArgumentValue(new ArgumentValue(pType, pName, pValue));
            }
            beanDefinition.setConstructorArgumentValues(AVS);
            //end of handle constructor
            this.simpleBeanFactory.registerBeanDefinition(beanID, beanDefinition);
        }
    }
}
